package com.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.DateUtils;
import com.common.easyui.EasyuiUtils;
import com.common.easyui.JsonTreeData;
import com.common.http.HttpResult;
import com.dao.sys.SysDictMapper;
import com.model.sys.SysDict;
import com.service.sys.SysDictService;

/**
 * @author lijiazhen
 * @date 2022-02-21 param description
 */
@Controller
@RequestMapping(value = "/api")
public class SysDictController {
	static final Logger logger = LoggerFactory.getLogger(DeptManageController.class);

	@Autowired
	private SysDictService sysDictService;
	@Autowired
	private SysDictMapper sysDictMapper;
	@Autowired
	private SysDictMapper SysDictMapper;

	/**
	 * 新增
	 *
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	@RequestMapping(value = "/sysDict/insert", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String insert(HttpServletRequest request) {
		try {
			int i = 0;
			String dicName = request.getParameter("dicName");
			String remark = request.getParameter("remark");
			String dicSort = request.getParameter("dicSort");
			String status = request.getParameter("status");
			String dicId = request.getParameter("dicId");
			String userId = request.getParameter("userId");
			String userName = request.getParameter("userName");
			if (StringUtils.isEmpty(dicName)) {
				return "字典名不得为空";
			}

			Map params = new HashMap();
			params.put("dicName", dicName);
			SysDict sysDict = new SysDict();
			sysDict.setDicName(dicName);
			sysDict.setRemark(StringUtils.isNotBlank(remark) ? remark : "");
			sysDict.setStatus(status);
			sysDict.setDicSort(Integer.valueOf(dicSort));
			sysDict.setDicParentId("0");
			sysDict.setDelFlag("0");

			if (StringUtils.isBlank(dicId)) {
				params.put("dicParentId", "0");
				List<SysDict> counts = sysDictService.selectDictListByParams(params);
				if (counts.size() >= 1) {
					return "字典名已存在";
				} else {
					dicId = UUID.randomUUID().toString();
					sysDict.setDicId(dicId);
					sysDict.setCreateTime(DateUtils.getCurrentTime());
					sysDict.setCreateId(userId);
					sysDict.setCreateName(userName);
					i = sysDictMapper.insert(sysDict);
				}
			} else {
				params.put("dicParentId", "0");
				params.put("dicId", dicId);
				List<SysDict> counts = sysDictService.selectDictListByParams(params);
				if (counts.size() > 1) {
					return "字典名已存在";
				} else {
					sysDict.setDicId(dicId);
					sysDict.setUpdateId(userId);
					sysDict.setUpdateName(userName);
					sysDict.setUpdateTime(DateUtils.getCurrentTime());
					i = sysDictMapper.update(sysDict);
				}
			}
			return i > 0 ? "保存成功" : "保存失败";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}

	}

	/**
	 * 刪除
	 * 
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	/*
	 * @RequestMapping("/delete")
	 * 
	 * public ReturnT<String> delete(int id){ return sysDictService.delete(id); }
	 */

	/**
	 * 更新
	 * 
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	/*
	 * @RequestMapping("/update") public ReturnT<String> update(SysDict sysDict){
	 * return sysDictService.update(sysDict); }
	 */

	/**
	 * 查询 根据主键 id 查询
	 * 
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	/*
	 * @RequestMapping("/load") public Object load(int id){ return
	 * sysDictService.load(id); }
	 */

	/**
	 * 查询 分页查询
	 *
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	@RequestMapping(value = "/sysDict/pageList", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String pageList(HttpServletRequest httpServletRequest) {
		try {
			List<SysDict> list = SysDictMapper.pageList();
			String jsonString = EasyuiUtils.getOwnTreeGridJson(list, "dicId", "dicParentId", "root", "0");
			// String jsonString = EasyuiUtils.getTreeGridJson(list, "dicId", "dicParentId",
			// "0");
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			httpServletRequest.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/sysDict/selectTreeList", method = { RequestMethod.POST })
	@ResponseBody
	public String selectTreeList(@RequestParam(value = "id", required = false) String id) {
		return sysDictService.selectTreeList(id);
	}

	/**
	 * 根据参数查询列表
	 *
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/sysDict/selectDictListByParams", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult selectList(@RequestParam Map<String, Object> map) {
		HttpResult httpResult = new HttpResult();
		httpResult.setRows(sysDictService.selectDictListByParams(map));
		return httpResult;
	}

	/**
	 * 删除字典大类，同时删除子类
	 *
	 * @param request dicId 字典ID
	 * @return
	 */
	@RequestMapping(value = "/sysDict/delDictClassesByPrimaryKey", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String delDictClassesByPrimaryKey(HttpServletRequest request) {
		try {
			String result = "";
			String dicId = request.getParameter("dicId");
			String userName = request.getParameter("userName");
			String userId = request.getParameter("userId");
			if (StringUtils.isBlank(dicId)) {
				return "字典ID不得为空！";
			}
			Map params = new HashMap();
			params.put("dicId", dicId);
			params.put("updateName", userName);
			params.put("updateId", userId);
			params.put("updateTime", DateUtils.getCurrentDate());
			result = sysDictMapper.delDictClassesByPrimaryKey(params) > 0 ? "保存成功!" : "保存失败!";
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/sysDict/DictListJson_combobox", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String DeptListJson_combobox(HttpServletRequest request) {
		try {
			List<SysDict> list = sysDictMapper.pageList();
//			String jsonString = EasyuiHelper.getCobTreeJson(list, "deptid", "dwmc", "parentid", modelDept.getParentid(),
//					"", false);

			List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
			for (SysDict sysDict : list) {
				JsonTreeData treeData = new JsonTreeData();
				treeData.setId(sysDict.getDicId());
				treeData.setPid(sysDict.getDicParentId());
				treeData.setText(sysDict.getDicName());
				treeDataList.add(treeData);
			}
			List<JsonTreeData> newTreeDataList = EasyuiUtils.getTreeJson(treeDataList, "0", "");
			String slist = JSON.toJSONString(newTreeDataList);

			logger.info("DeptListJson_combobox:{}", slist);
			request.setAttribute("addLists", list);

			return slist;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}
	}

	/**
	 * 新增字典子项
	 *
	 * @author lijiazhen
	 * @date 2022/02/22
	 **/
	@RequestMapping(value = "/sysDict/insertItemDict", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String insertItemDict(HttpServletRequest request) {
		try {
			int i = 0;
			String dicName = request.getParameter("dicName");
			String dicValue = request.getParameter("dicValue");
			String remark = request.getParameter("remark");
			String dicSort = request.getParameter("dicSort");
			String status = request.getParameter("status");
			String dicId = request.getParameter("dicId");
			String userId = request.getParameter("userId");
			String userName = request.getParameter("userName");
			String parentId = request.getParameter("dicParentId");
			if (StringUtils.isEmpty(dicName)) {
				return "字典名不得为空";
			}
			Map params = new HashMap();
			params.put("dicName", dicName);
			SysDict sysDict = new SysDict();
			sysDict.setDicName(dicName);
			sysDict.setRemark(StringUtils.isNotBlank(remark) ? remark : "");
			sysDict.setStatus(status);
			sysDict.setDicValue(dicValue);

			sysDict.setDicSort(Integer.valueOf(dicSort));
			sysDict.setDicParentId(parentId);
			sysDict.setDelFlag("0");

			if (StringUtils.isBlank(dicId)) {
				params.put("parentId", parentId);
				List<SysDict> counts = sysDictService.selectDictListByParams(params);
				if (counts.size() >= 1) {
					return "字典名已存在";
				} else {
					dicId = UUID.randomUUID().toString();
					sysDict.setDicId(dicId);
					sysDict.setCreateTime(DateUtils.getCurrentTime());
					sysDict.setCreateId(userId);
					sysDict.setCreateName(userName);
					i = sysDictMapper.insert(sysDict);
				}
			} else {
				params.put("parentId", parentId);
				params.put("dicId", dicId);
				List<SysDict> counts = sysDictService.selectDictListByParams(params);
				if (counts.size() > 1) {
					return "字典名已存在";
				} else {
					sysDict.setDicId(dicId);
					sysDict.setUpdateId(userId);
					sysDict.setUpdateName(userName);
					sysDict.setUpdateTime(DateUtils.getCurrentTime());
					i = sysDictMapper.update(sysDict);
				}
			}
			return i > 0 ? "保存成功" : "保存失败";
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return e.getMessage();
		}

	}

	/**
	 * 根据字典大类名字查询下属字典项
	 */
	@RequestMapping(value = "sysDict/queryItemByTypeName", method = { RequestMethod.GET })
	@ResponseBody
	public List queryItemByTypeName(@RequestParam String dicName) {
		return sysDictService.queryItemByTypeName(dicName);
	}

	/**
	 * 查询到货地点得字典dataGrid
	 */
	@RequestMapping(value = "sysDict/queryAddress", method = { RequestMethod.POST })
	@ResponseBody
	public List queryAddress(@RequestParam Map param) {
		return sysDictService.queryItemByTypeName(param);
	}
}
